# -*- coding: utf-8 -*-

import httplib
import urllib
import urllib2
import cookielib
import json
import urlparse
import re
import sys
import time
import pytesser

class configuration(object):
    Username = ''
    Password = ''
    
    def __init__(self, username, password):
        self.Username = username
        self.Password = password
    
    def get_username(self):
        return self.Username
    
    def get_password(self):
        return self.Password

def check_ipv6_access():
    access = httplib.HTTPConnection("ipv6.google.com")
    access.request("GET", "/")
    response = access.getresponse()
    if response.status == 302:
        location = response.msg.dict["location"]
        if location.find('auth-1') >= 0:
            return False
    return True

def ipv6_login(config):
    access = httplib.HTTPConnection("ipv6.google.com")
    access.request("GET", "/")
    response = access.getresponse()
    location = ''
    if response.status == 302:
        location = response.msg.dict["location"]
        if location.find('auth-1') == -1:
            return
    # Accessing IPv6 logging page
    cookie_jar = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
    opener.open(location)
    # Get the authcode
    authcode_url = 'https://auth-1.ccert.edu.cn:8443/eportal/validcode'
    req = opener.open(authcode_url)
    data = req.read()
    f = open('authcode.gif', 'wb')
    f.write(data)
    f.close()
    im = pytesser.Image.open('authcode.gif')
    authcode = pytesser.image_to_string(im)
    authcode = authcode.replace('\n', '')
    print '[thu-ipv6-login]Authcode: ' + authcode
    # Build request and post it
    url_component = urlparse.urlparse(location)
    query_component = urlparse.parse_qs(url_component.query)
    query_s = query_component['s'][0]
    query_mac = query_component['mac'][0]
    query_port = query_component['port'][0]
    query_url = query_component['url'][0]
    login_url = 'https://auth-1.ccert.edu.cn:8443/eportal/user.do?method=login_ajax&username=%s&pwd=%s&isp=&s=%s&url=%s&port=%s&mac=%s&validcode=%s&is_check=false' \
                % (config.get_username(), config.get_password(), query_s, query_url, query_port, query_mac, authcode)
    req = opener.open(login_url)
    response = req.read()
    if response == '':
        print '[thu-ipv6-login]Login failed.  Response is null.'
        return
    # lazy json data processing
    response = re.sub(r"([^{\s:,]+):[\s]*'([^']*)'", r'"\1":"\2"', response)
    json_data = json.loads(response)
    is_successful = json_data['isAuthSuccess']
    if is_successful == 'success':
        print '[thu-ipv6-login]Login succeeded.'
    else:
        message = json_data['message']
        print '[thu-ipv6-login]Login failed. Message: %s' % json_data['message']
        return
    
    # Get user token
    req_loginsucceed = opener.open('https://auth-1.ccert.edu.cn:8443/eportal/loginsuccess.jsp')
    user_token = ''
    response = req_loginsucceed.read()
    user_token_pre = re.compile(r"name=\"userIndex\"[\s]+value='([^'\s]*)'")
    user_token_match = user_token_pre.search(response)
    if user_token_match:
        user_token = user_token_match.group(1)
    print '[thu-ipv6-login]User token: %s' % user_token
    
    # Refresh every 1 min
    # print '[logger]Refresh frequently...'

if __name__ == "__main__":
    if not check_ipv6_access():
        print '[thu-ipv6-login]Logging in is needed for IPv6.'
        if len(sys.argv) < 2:
            print '[thu-ipv6-login]Error: please run this script with username and password.'
        else:
            username = sys.argv[1]
            password = sys.argv[2]
            print '[thu-ipv6-login]Username: ' + username
            config = configuration(username, password)
            ipv6_login(config)
    else:
        print '[thu-ipv6-login]Logging in is not needed.'
